package com.yanfan.energy.controller;

import java.text.SimpleDateFormat;
import java.util.*;
import javax.validation.Valid;
import javax.servlet.http.HttpServletResponse;

import com.yanfan.common.utils.DateUtils;
import com.yanfan.energy.mapper.IbmsEnergyDeviceDataMapper;
import com.yanfan.energy.vo.EnergyFlowRecord;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.yanfan.common.annotation.Log;
import com.yanfan.common.core.controller.BaseController;
import com.yanfan.common.core.domain.AjaxResult;
import com.yanfan.common.enums.BusinessType;
import com.yanfan.energy.domain.IbmsEnergyDeviceData;
import com.yanfan.energy.service.IIbmsEnergyDeviceDataService;
import com.yanfan.common.utils.poi.ExcelUtil;
import com.yanfan.common.core.page.TableDataInfo;

/**
 * 能耗设备数据Controller
 *
 * @author genluo
 * @date 2024-09-22
 */
@Api(tags = "能耗设备数据")
@RestController
@RequestMapping("/energy/data")
public class IbmsEnergyDeviceDataController extends BaseController {
    @Autowired
    private IIbmsEnergyDeviceDataService ibmsEnergyDeviceDataService;

    @Autowired
    private IbmsEnergyDeviceDataMapper ibmsEnergyDeviceDataMapper;

    /**
     * 查询能耗设备数据列表
     */
    @ApiOperation("能耗设备数据分页列表")
    @PreAuthorize("@ss.hasPermi('energy:data:list')")
    @GetMapping("/list")
    public TableDataInfo list(IbmsEnergyDeviceData ibmsEnergyDeviceData) {
        startPage();
        List<IbmsEnergyDeviceData> list = ibmsEnergyDeviceDataService.queryPageList(ibmsEnergyDeviceData);
        return getDataTable(list);
    }

    /**
     * 导出能耗设备数据列表
     */
    @ApiOperation("导出能耗设备数据列表")
    @PreAuthorize("@ss.hasPermi('energy:data:export')")
    @Log(title = "能耗设备数据", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, IbmsEnergyDeviceData ibmsEnergyDeviceData) {
        List<IbmsEnergyDeviceData> list = ibmsEnergyDeviceDataService.queryPageList(ibmsEnergyDeviceData);
        ExcelUtil<IbmsEnergyDeviceData> util = new ExcelUtil<IbmsEnergyDeviceData>(IbmsEnergyDeviceData.class);
        util.exportExcel(response, list, "能耗设备数据数据");
    }

    /**
     * 获取能耗设备数据详细信息
     */
    @ApiOperation("获取能耗设备数据详细信息")
    @PreAuthorize("@ss.hasPermi('energy:data:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(ibmsEnergyDeviceDataService.getById(id));
    }

    /**
     * 新增能耗设备数据
     */
    @ApiOperation("新增能耗设备数据")
    @PreAuthorize("@ss.hasPermi('energy:data:add')")
    @Log(title = "能耗设备数据", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Valid @RequestBody IbmsEnergyDeviceData ibmsEnergyDeviceData) {
        return toAjax(ibmsEnergyDeviceDataService.save(ibmsEnergyDeviceData));
    }

    /**
     * 修改能耗设备数据
     */
    @ApiOperation("修改能耗设备数据")
    @PreAuthorize("@ss.hasPermi('energy:data:edit')")
    @Log(title = "能耗设备数据", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Valid @RequestBody IbmsEnergyDeviceData ibmsEnergyDeviceData) {
        return toAjax(ibmsEnergyDeviceDataService.updateById(ibmsEnergyDeviceData));
    }

    /**
     * 删除能耗设备数据
     */
    @ApiOperation("删除能耗设备数据")
    @PreAuthorize("@ss.hasPermi('energy:data:remove')")
    @Log(title = "能耗设备数据", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(ibmsEnergyDeviceDataService.removeBatchByIds(Arrays.asList(ids)));
    }


    @GetMapping("/energyFlow")
    public AjaxResult energyFlow(){
        String year = DateUtils.parseDateToStr("yyyy-MM-dd HH", new Date());

        //电表有功电量
        ArrayList<String> list = new ArrayList<>();
        List<EnergyFlowRecord> ibmsEnergyDeviceDataList = new ArrayList<>();
        list.add("11X");
        EnergyFlowRecord ammeterValue = ibmsEnergyDeviceDataMapper.energyFlow(year,list);
        ammeterValue.setEnergyDeviceName("11X");
        if (ammeterValue == null){
            EnergyFlowRecord energyFlowRecord = new EnergyFlowRecord();
            energyFlowRecord.setEnergyDeviceName("11X");
            energyFlowRecord.setEnergyValue("0");
            ibmsEnergyDeviceDataList.add(energyFlowRecord);
        }else {
            ammeterValue.setEnergyDeviceName("11X");
            ibmsEnergyDeviceDataList.add(ammeterValue);
        }
        list.clear();
        list.add("12L");
        EnergyFlowRecord waterMeterValue = ibmsEnergyDeviceDataMapper.energyFlow(year,list);
        if (waterMeterValue == null){
            EnergyFlowRecord energyFlowRecord = new EnergyFlowRecord();
            energyFlowRecord.setEnergyDeviceName("12L");
            energyFlowRecord.setEnergyValue("0");
            ibmsEnergyDeviceDataList.add(energyFlowRecord);
        }else {
            waterMeterValue.setEnergyDeviceName("12L");
            ibmsEnergyDeviceDataList.add(waterMeterValue);
        }
        list.clear();
        list.add("12N");
        list.add("12O");
        EnergyFlowRecord airValue = ibmsEnergyDeviceDataMapper.energyFlow(year,list);
        if (airValue == null){
            EnergyFlowRecord energyFlowRecord = new EnergyFlowRecord();
            energyFlowRecord.setEnergyDeviceName("12N");
            energyFlowRecord.setEnergyValue("0");
            ibmsEnergyDeviceDataList.add(energyFlowRecord);
        }else {
            airValue.setEnergyDeviceName("12N");
            ibmsEnergyDeviceDataList.add(airValue);
        }

        return AjaxResult.success(ibmsEnergyDeviceDataList);
    }

    @ApiOperation("查询能耗设备当日数据")
    @GetMapping("/energyDayFlow")
    public AjaxResult energyDayFlow(){

        try {

            // 获取当前时间
            Calendar calendar = Calendar.getInstance();

            // 将时间减去一个小时
            calendar.add(Calendar.HOUR_OF_DAY, -1);

            // 获取前一个小时的时间
            Date oneHourAgo = calendar.getTime();

            // 创建日期格式化对象
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH");

            // 将日期格式化为字符串
            String formattedDate = dateFormat.format(oneHourAgo);

            String year = DateUtils.parseDateToStr("yyyy-MM-dd HH", new Date());
            //电表有功电量
            ArrayList<String> list = new ArrayList<>();
            List<EnergyFlowRecord> ibmsEnergyDeviceDataList = new ArrayList<>();
            List<EnergyFlowRecord> ibmsEnergyDeviceDataList1 = new ArrayList<>();
            list.add("11X");
            EnergyFlowRecord ammeterFlowValue = ibmsEnergyDeviceDataMapper.energyFlow(formattedDate, list);
            EnergyFlowRecord ammeterValue = ibmsEnergyDeviceDataMapper.energyFlow(year, list);
            ammeterFlowValue.setEnergyDeviceName("11X");
            ammeterValue.setEnergyDeviceName("11X");
            if (ammeterValue == null) {
                EnergyFlowRecord energyFlowRecord = new EnergyFlowRecord();
                energyFlowRecord.setEnergyDeviceName("11X");
                energyFlowRecord.setEnergyValue("0");
                ibmsEnergyDeviceDataList.add(energyFlowRecord);
            } else {
                ammeterValue.setEnergyDeviceName("11X");
                ibmsEnergyDeviceDataList.add(ammeterValue);
            }

            if (ammeterFlowValue == null) {
                EnergyFlowRecord energyFlowRecord = new EnergyFlowRecord();
                energyFlowRecord.setEnergyDeviceName("11X");
                energyFlowRecord.setEnergyValue("0");
                ibmsEnergyDeviceDataList1.add(energyFlowRecord);
            } else {
                ammeterFlowValue.setEnergyDeviceName("11X");
                ibmsEnergyDeviceDataList1.add(ammeterFlowValue);
            }

            list.clear();
            list.add("12L");
            EnergyFlowRecord waterMeterValue = ibmsEnergyDeviceDataMapper.energyFlow(year, list);
            if (waterMeterValue == null) {
                EnergyFlowRecord energyFlowRecord = new EnergyFlowRecord();
                energyFlowRecord.setEnergyDeviceName("12L");
                energyFlowRecord.setEnergyValue("0");
                ibmsEnergyDeviceDataList.add(energyFlowRecord);
            } else {
                waterMeterValue.setEnergyDeviceName("12L");
                ibmsEnergyDeviceDataList.add(waterMeterValue);
            }

            list.clear();
            list.add("12L");
            EnergyFlowRecord waterFolwMeterValue = ibmsEnergyDeviceDataMapper.energyFlow(formattedDate, list);
            if (waterFolwMeterValue == null) {
                EnergyFlowRecord energyFlowRecord = new EnergyFlowRecord();
                energyFlowRecord.setEnergyDeviceName("12L");
                energyFlowRecord.setEnergyValue("0");
                ibmsEnergyDeviceDataList1.add(energyFlowRecord);
            } else {
                waterFolwMeterValue.setEnergyDeviceName("12L");
                ibmsEnergyDeviceDataList1.add(waterFolwMeterValue);
            }

            /*
            * 查询当前小时空调能耗数据
            * */
            list.clear();
            list.add("12N");
            list.add("12O");
            EnergyFlowRecord airValue = ibmsEnergyDeviceDataMapper.energyFlow(year, list);
            if (airValue == null) {
                EnergyFlowRecord energyFlowRecord = new EnergyFlowRecord();
                energyFlowRecord.setEnergyDeviceName("12N");
                energyFlowRecord.setEnergyValue("0");
                ibmsEnergyDeviceDataList.add(energyFlowRecord);
            } else {
                airValue.setEnergyDeviceName("12N");
                ibmsEnergyDeviceDataList.add(airValue);
            }

            /*查询前一个小时空调能耗数据
            * */
            list.clear();
            list.add("12N");
            list.add("12O");
            EnergyFlowRecord airFolwValue = ibmsEnergyDeviceDataMapper.energyFlow(formattedDate, list);
            if (airFolwValue == null) {
                EnergyFlowRecord energyFlowRecord = new EnergyFlowRecord();
                energyFlowRecord.setEnergyDeviceName("12N");
                energyFlowRecord.setEnergyValue("0");
                ibmsEnergyDeviceDataList1.add(energyFlowRecord);
            } else {
                airFolwValue.setEnergyDeviceName("12N");
                ibmsEnergyDeviceDataList1.add(airFolwValue);
            }

            // 计算差值
            Map<String, Double> energyDifferences = calculateEnergyDifferences(ibmsEnergyDeviceDataList, ibmsEnergyDeviceDataList1);

            return AjaxResult.success(energyDifferences);
        }catch (Exception e) {
            e.printStackTrace();
            // 计算差值
            Map<String, Double> energyDifferences = calculateEnergyDifferences(null, null);
            energyDifferences.put("11X",0.0);
            energyDifferences.put("12L",0.0);
            energyDifferences.put("12N",0.0);
            return AjaxResult.success(energyDifferences);
        }
    }


    public static Map<String, Double> calculateEnergyDifferences(List<EnergyFlowRecord> currentList, List<EnergyFlowRecord> previousList) {
        Map<String, Double> currentValues = new HashMap<>();
        Map<String, Double> previousValues = new HashMap<>();

        // 将当前列表中的数据放入 map
        for (EnergyFlowRecord record : currentList) {
            currentValues.put(record.getEnergyDeviceName(), Double.parseDouble(record.getEnergyValue()));
        }

        // 将前一个小时的列表中的数据放入 map
        for (EnergyFlowRecord record : previousList) {
            previousValues.put(record.getEnergyDeviceName(), Double.parseDouble(record.getEnergyValue()));
        }

        // 计算差值
        Map<String, Double> differences = new HashMap<>();
        for (String deviceName : currentValues.keySet()) {
            double currentValue = currentValues.get(deviceName);
            double previousValue = previousValues.getOrDefault(deviceName, 0.0);
            differences.put(deviceName, currentValue - previousValue);
        }

        return differences;
    }


}
